<template>
  <div class="page-header-index-wide" :style="{ minHeight: `${layoutContentHeight - pageHeaderHeight - 24}px` }">
    <a-card :bordered="false" :bodyStyle="{ padding: '16px 0', height: '100%' }" :style="{ height: '100%' }">
      <a-spin :spinning="confirmLoading">
        <a-form :form="form" v-bind="formItemLayout" @submit="handleSubmit">
          <a-form-item :label="$t('modules.user.oldPass')">
            <a-input-password
              :disabled="!$auth('edit', this.$route.meta.permissionId)"
              autocomplete="off"
              :spell-check="false"
              v-decorator="[
                'oldPassword',
                {
                  rules: [{ required: true, message: $t('common.emptyErr', { name: $t('modules.user.oldPass') }) }]
                }
              ]"
              type="password"
            />
          </a-form-item>
          <a-form-item>
            <span slot="label">
              {{ $t('modules.user.newPass') }}
              <a-tooltip :title="passwordTips">
                <a-icon type="question-circle-o" />
              </a-tooltip>
            </span>
            <a-input-password
              :disabled="!$auth('edit', this.$route.meta.permissionId)"
              :maxLength="passwordInfo.passwordMax"
              autocomplete="off"
              :spell-check="false"
              v-decorator="[
                'newPassword',
                {
                  rules: [
                    { required: true, message: $t('common.emptyErr', { name: $t('common.password') }) },
                    {
                      min: passwordInfo.passwordMin,
                      max: passwordInfo.passwordMax,
                      message: $t('modules.user.passwordLengthErr')
                    },
                    { validator: validateToNextPassword }
                  ]
                }
              ]"
              type="password"
            />
          </a-form-item>
          <a-form-item :label="$t('modules.user.confirmPass')">
            <a-input-password
              :disabled="!$auth('edit', this.$route.meta.permissionId)"
              :maxLength="passwordInfo.passwordMax"
              autocomplete="off"
              :spell-check="false"
              v-decorator="[
                'confirmPassword',
                {
                  rules: [{ required: true, message: '请再次输入密码！' }, { validator: compareToFirstPassword }]
                }
              ]"
              type="password"
              @blur="handleConfirmBlur"
            />
          </a-form-item>
          <a-form-item v-action:edit class="footer" :wrapper-col="{ offset: 4, span: 12 }">
            <a-button style="margin-right: 8px;" @click="handleCancel">{{ $t('common.cancel') }}</a-button>
            <a-button type="primary" html-type="submit" :loading="confirmLoading">{{ $t('common.update') }}</a-button>
          </a-form-item>
        </a-form>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { layoutMixin } from '@/utils/mixin'
import { mapActions } from 'vuex'
import { getSystemSecurity } from '@/api/authenticationCenter/SystemSecurityController'
import md5 from 'md5'
const SIMPLE = new RegExp('^(\\d|[a-zA-Z])*((\\d[a-zA-Z])|([a-zA-Z]\\d))(\\d|[a-zA-Z])*$')
const COMPLEX = new RegExp(
  '^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{6,}$'
)
export default {
  name: 'AccountSecurity',
  mixins: [layoutMixin],
  data () {
    return {
      confirmLoading: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 }
        }
      },
      SIMPLE: SIMPLE,
      COMPLEX: COMPLEX,
      confirmDirty: false,
      passwordInfo: {
        passwordMin: 6,
        passwordMax: 12,
        passwordRule: 'SIMPLE'
      }
    }
  },
  computed: {
    passwordTips () {
      const passwordRule = {
        SIMPLE: this.$t('authenticationCenter.securityConfiguration.numbersAndeLetters'),
        COMPLEX: this.$t('authenticationCenter.securityConfiguration.numbersOrLettersOrcharacter')
      }
      const str = `${this.$t('modules.user.passwordLength')}${this.passwordInfo.passwordMin}-${
        this.passwordInfo.passwordMax
      },${passwordRule[this.passwordInfo.passwordRule]}`
      return str
    }
  },
  created () {
    this.getSystemSecurity()
  },
  methods: {
    ...mapActions(['UpdatePassword']),
    // 获取安全配置
    getSystemSecurity () {
      getSystemSecurity().then(res => {
        if (res.data) {
          this.passwordInfo = res.data
        }
      })
    },
    handleConfirmBlur (e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    validateToNextPassword (rules, value, callback) {
      const {
        form: { validateFields },
        confirmDirty
      } = this
      if (confirmDirty) {
        validateFields(['confirmPassword'], { force: true })
      }
      if (value) {
        const passwordRule = {
          SIMPLE: this.$t('authenticationCenter.securityConfiguration.numbersAndeLetters'),
          COMPLEX: this.$t('authenticationCenter.securityConfiguration.numbersOrLettersOrcharacter')
        }
        if (this.passwordInfo.passwordRule === 'COMPLEX') {
          if (value.length >= this.passwordInfo.passwordMin && value.length <= this.passwordInfo.passwordMax) {
            if (
              /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{6,}$/.test(
                value
              )
            ) {
              callback()
            } else {
              callback(passwordRule[this.passwordInfo.passwordRule])
            }
          } else {
            callback(passwordRule[this.passwordInfo.passwordRule])
          }
        } else if (this.passwordInfo.passwordRule === 'SIMPLE') {
          if (
            value.length >= this.passwordInfo.passwordMin &&
            value.length <= this.passwordInfo.passwordMax &&
            /[\d]/.test(value) &&
            /[a-zA-z]/.test(value)
          ) {
            callback()
          } else {
            callback(passwordRule[this.passwordInfo.passwordRule])
          }
        }
      } else {
        callback()
      }
    },
    compareToFirstPassword (rules, value, callback) {
      const {
        form: { getFieldValue }
      } = this
      if (value && getFieldValue('newPassword') && value !== getFieldValue('newPassword')) {
        callback('两次输入的密码不一致！')
      } else {
        callback()
      }
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          const req = { ...values }
          for (const key in req) {
            req[key] = md5(req[key])
          }

          this.UpdatePassword(req)
            .then(() => {
              this.$message.success('密码修改成功, 请重新登录！', 2, () => {
                window.location.reload()
              })
            })
            .finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      if (this.confirmLoading) return
      this.confirmDirty = false
      const {
        form: { resetFields }
      } = this
      resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.footer {
  text-align: right;
}
</style>
